package cn.bj.xd.boot.autoconfigure;

import cn.bj.xd.mdy.core.WorkSheetClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Slf4j
@Configuration
public class WorkSheetClientRegistrar implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {

    private Environment environment;
    private MdyProperties properties;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        if (properties == null) {
            return;
        }
        properties.getApplication().forEach((key, config) -> {
            BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(WorkSheetClient.class).addConstructorArgValue(config.getAddress()).addConstructorArgValue(config.getApiKey()).addConstructorArgValue(config.getSign()).setScope(BeanDefinition.SCOPE_PROTOTYPE).getBeanDefinition();
            beanDefinitionRegistry.registerBeanDefinition(key + "WorkSheetClient", beanDefinition);
        });
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        log.info("register WorkSheetClient count {} ", configurableListableBeanFactory.getBeanDefinitionCount());
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
        this.properties = Binder.get(environment).bind("mingdao", MdyProperties.class).orElseThrow(() -> new IllegalArgumentException("mingdao properties not found"));

    }
}
